package com.mvvm.ktnet.ui.testScrollView

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Rect
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.view.animation.AccelerateInterpolator
import android.view.animation.TranslateAnimation
import android.widget.ScrollView
import androidx.core.widget.NestedScrollView


class MyScrollView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyle: Int = 0
) : NestedScrollView(context, attrs, defStyle) {

    private var previousY = 0
    private var startY = 0
    private var currentY = 0
    private var deltaY = 0
    private var childView: View? = null
    private val topRect: Rect = Rect()


    @SuppressLint("MissingSuperCall")
    override fun onFinishInflate() {
        if (childCount > 0) {
            childView = getChildAt(0)
        }
    }

    override fun dispatchTouchEvent(event: MotionEvent): Boolean {
        if (null == childView) {
            return super.dispatchTouchEvent(event)
        }
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                startY = event.y.toInt()
                previousY = startY
            }
            MotionEvent.ACTION_MOVE -> {
                currentY = event.y.toInt()
                deltaY = previousY - currentY
                previousY = currentY
                if (0 == scrollY
                    || childView!!.measuredHeight - height <= scrollY
                ) {
                    if (topRect.isEmpty) {
                        topRect.set(
                            childView!!.left, childView!!.top,
                            childView!!.right, childView!!.bottom
                        )
                    }
                    childView!!.layout(
                        childView!!.left, childView!!.top
                                - deltaY / 3, childView!!.right,
                        childView!!.bottom - deltaY / 3
                    )
                }
            }
            MotionEvent.ACTION_UP -> {
                if (!topRect.isEmpty) {
                    upDownMoveAnimation()
                    // 子控件回到初始位置
                    childView!!.layout(
                        topRect.left, topRect.top, topRect.right,
                        topRect.bottom
                    )
                }
                startY = 0
                currentY = 0
                topRect.setEmpty()
            }
            else -> {
            }
        }
        return super.dispatchTouchEvent(event)
    }
    private fun upDownMoveAnimation() {
        val animation = TranslateAnimation(
            0.0f,
            0.0f,
            childView?.top?.toFloat() ?: 0f,
            topRect.top.toFloat()
        )
        animation.duration = 100
        animation.interpolator = AccelerateInterpolator()
        childView?.animation = animation
    }
}